package org.luosl.webmagicx.handler

import org.luosl.webmagicx.conf.{SpiderConf, XmlProps}
import org.luosl.webmagicx.utils.Logging
import org.luosl.webmagicx.listeners.{HandlerListener, PipelineListener}
import us.codecraft.webmagic.{ResultItems, Task}
import us.codecraft.webmagic.handler.Handler

import scala.collection.mutable.ArrayBuffer

/**
  * Created by luosl on 2017/12/18.
  */
abstract class AbstractHandler(sc:SpiderConf, task:Task, props:XmlProps) extends Handler with Logging{
  /**
    * 监听器
    */
  protected var listeners:ArrayBuffer[HandlerListener] = ArrayBuffer.empty[HandlerListener]

  /**
    * 添加一个监听器
    * @param listener listener
    * @return
    */
  def addListener(listener:HandlerListener):AbstractHandler = {
    listeners += listener
    this
  }

  def onSkip(resultItems: ResultItems, task: Task): Unit ={
    listeners.foreach(ls=>ls.onSkip(resultItems, task))
  }

  def onError(resultItems: ResultItems, task: Task, exception: Exception): Unit ={
    listeners.foreach(ls=>ls.onError(resultItems, task))
  }

  def onSuccess(resultItems: ResultItems, task: Task): Unit ={
    listeners.foreach(ls=>ls.onSuccess(resultItems, task))
  }

  override def process(items: ResultItems, task: Task): Unit = {
    try{
      processHandle(items, task)
      if(items.isSkip) onSkip(items, task) else onSuccess(items, task)
    }catch { case e:Exception => onError(items, task, e) }
  }

  /**
    * 执行处理
    * @param items items
    * @param task task
    */
  def processHandle(items: ResultItems, task: Task): Unit

}
